﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SLAU;

namespace Solvers
{
    public class ZeidelSolver : Solver
    {
        public ZeidelSolver(SLAU.SLAU system, double precision)
            : base(system, precision)
        {
            this.StartVector = system.StartVector;
            this.System.Normalize();
        }

        public Vector StartVector { get; set; }

        public override void Solve()
        {
            if (!this.System.CheckConvergence())
            {
                return;
            }

            int n = this.System.EquationsCount;
            Vector free = this.System.Free;
            Matrix coeff = this.System.Coefficients;

            Vector tmp = new Vector(n);
            Vector stor = new Vector(free);

            double ok;
            int iter=0;
            do
            {
                for (int i = 0; i < n; i++)
                {
                    tmp[i] = 0;
                    for (int j = 0; j < n; j++)
                    {
                        tmp[i] += coeff[i, j] * stor[j];
                    }
                    tmp[i] += free[i];
                    stor[i] = tmp[i];
                }
                ok = Math.Abs(this.StartVector[0] - tmp[0]);

                for (int i = 0; i < n; i++)
                {
                    if (Math.Abs(this.StartVector[i] - tmp[i]) > ok)
                    {
                        ok = Math.Abs(this.StartVector[i] - tmp[i]);
                    }
                    this.StartVector[i] = tmp[i];
                }
                Console.WriteLine(iter++);
            } while (ok > this.Precision);

            this.Solution = new Vector(tmp);
            this.Solved = true;
        }
    }
}
